import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import AboutView from '@/views/AboutView.vue'
import store from "@/store";
import { Tool } from "@/utils/tool";
import { message } from "ant-design-vue";

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/admin/user',
    name: 'AdminUser',
    component: () => import('../views/admin/admin-user.vue'),
    meta: {
      loginRequire: true // 添加登录要求标记
    }
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  },
  {
    path: '/admin/ebook',
    name: 'AdminEbook',
    component: () => import('../views/admin/admin-ebook.vue'),
    meta: {
      loginRequire: true // 添加登录要求标记
    }
  },
  {
    path: '/admin/category',
    name: 'AdminCategory',
    component: () => import('../views/admin/admin-category.vue'),
    meta: {
      loginRequire: true // 添加登录要求标记
    }
  },
  {
    path: '/admin/doc',
    name: 'AdminDoc',
    component: () => import('../views/admin/admin-doc.vue'),
    meta: {
      loginRequire: true // 添加登录要求标记
    }
  },
  {
    path: '/doc',
    name: 'Doc',
    component: () => import('../views/DocView.vue')
  },

  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由登录拦截 - 每次路由跳转前执行
router.beforeEach((to, from, next) => {
  // 检查目标路由是否需要登录
  const requiresLogin = to.matched.some(item => {
    return item.meta.loginRequire;
  });

  if (requiresLogin) {
    const loginUser = store.state.user;
    
    // 检查用户是否已登录
    if (Tool.isEmpty(loginUser)) {
      message.error("请登录！");
      next('/'); // 跳转到首页（或其他登录页面）
    } else {
      next(); // 已登录，继续导航
    }
  } else {
    next(); // 不需要登录，继续导航
  }
});

export default router